﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "修改BOM";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<script src="~/layui/layui.js"></script>
<script src="~/js/site.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>

<div class="layui-container" style="padding: 20px;">
    <div class="layui-row">
        <div class="layui-col-md12">
            <h2>修改BOM</h2>
        </div>
    </div>
    
    <!-- 修改BOM表单 -->
    <div class="layui-row">
        <div class="layui-col-md8 layui-col-md-offset2">
                         <form class="layui-form" id="updateBOMForm">
                
                <div class="layui-form-item">
                    <label class="layui-form-label">BOM主题</label>
                    <div class="layui-input-block">
                        <input type="text" name="boMtheme" lay-verify="required" placeholder="请输入BOM主题" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">BOM版本</label>
                    <div class="layui-input-block">
                        <input type="text" name="bomVersion" lay-verify="required" placeholder="请输入BOM版本" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">产品选择</label>
                    <div class="layui-input-block">
                        <select name="productId" lay-verify="required" lay-search>
                            <option value="">请选择产品</option>
                        </select>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">天数</label>
                    <div class="layui-input-block">
                        <input type="number" name="dayNum" lay-verify="required|number" placeholder="请输入天数" autocomplete="off" class="layui-input">
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">BOM描述</label>
                    <div class="layui-input-block">
                        <textarea name="bomDesc" lay-verify="required" placeholder="请输入BOM描述" class="layui-textarea"></textarea>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <label class="layui-form-label">BOM状态</label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="bomState" lay-skin="primary" title="启用" checked>
                    </div>
                </div>
                
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="updateBOMSubmit">
                            <i class="layui-icon layui-icon-ok"></i> 提交修改
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                                                 <button type="button" class="layui-btn layui-btn-warm" id="backToList">
                             <i class="layui-icon layui-icon-left"></i> 返回列表
                         </button>
                                     <a href="/Home/Index" class="layui-btn layui-btn-primary">
                <i class="layui-icon layui-icon-home"></i> 返回主页
            </a>
                         <button type="button" class="layui-btn layui-btn-normal" id="testApiBtn">
                             <i class="layui-icon layui-icon-refresh"></i> 测试API
                         </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 物料列表区域 -->
    <div class="layui-row" style="margin-top: 30px;">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>物料配件列表</h3>
                </div>
                <div class="layui-card-body">
                    <table id="materialTable" lay-filter="materialTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
layui.use(['form', 'layer', 'table'], function(){
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var bomRecords = []; // 全局变量存储BOM记录
    
         // 获取URL参数中的productId
     var urlParams = new URLSearchParams(window.location.search);
     var productId = urlParams.get('productId');
     
     if (!productId) {
         layer.msg('缺少产品ID参数', {icon: 2});
         return;
     }
    
    // 初始化物料表格
    function initMaterialTable() {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetMaterial',
            type: 'GET',
            success: function(response) {
                console.log('获取物料数据成功:', response);
                if (response.code === 200 && response.data) {
                    table.render({
                        elem: '#materialTable',
                        data: response.data,
                        page: true,
                        cols: [[
                            {type: 'checkbox', fixed: 'left'},
                            {field: 'materialId', title: '物料ID', width: 100, sort: true},
                            {field: 'materialName', title: '物料名称', width: 150},
                            {field: 'specification', title: '规格型号', width: 200},
                            {field: 'unitName', title: '单位', width: 80},
                            {field: 'brand', title: '品牌', width: 120},
                            {field: 'partNum', title: '配件数量', width: 120, templet: function(d){
                                return '<input type="number" class="layui-input part-num-input" data-id="'+d.materialId+'" placeholder="请输入" style="width:80px;">';
                            }},
                            {field: 'lossRate', title: '损耗率', width: 120, templet: function(d){
                                return '<input type="text" class="layui-input loss-rate-input" data-id="'+d.materialId+'" placeholder="请输入" style="width:80px;">';
                            }}
                        ]],
                        limits: [15, 30, 50, 100],
                        limit: 15,
                        height: 400,
                        done: function(res, curr, count) {
                            console.log('物料表格渲染完成:', res);
                        }
                    });
                } else {
                    console.error('物料数据格式错误:', response);
                }
            },
            error: function(xhr, status, error) {
                console.error('获取物料数据失败:', error);
            }
        });
    }
    
    // 初始化产品下拉框
    function initProductSelect() {
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetProduct',
            type: 'GET',
            success: function(response) {
                console.log('获取产品数据成功:', response);
                if (response.code === 200 && response.data) {
                    var select = $('select[name="productId"]');
                    select.empty();
                    select.append('<option value="">请选择产品</option>');
                    
                    response.data.forEach(function(product) {
                        select.append('<option value="' + product.productId + '">' + 
                                    product.productName + ' (' + product.productType + ')</option>');
                    });
                    
                    form.render('select');
                    console.log('产品下拉框初始化完成');
                    
                    // 产品下拉框初始化完成后，立即加载BOM数据
                    loadBOMData();
                } else {
                    console.error('产品数据格式错误:', response);
                }
            },
            error: function(xhr, status, error) {
                console.error('获取产品数据失败:', error);
            }
        });
    }
    
        // 加载BOM详情数据
    function loadBOMData() {
        // 首先需要获取产品ID，然后调用GetBOMOne API
        // 这里我们需要先获取BOM的基本信息来确定产品ID
        // 或者您可以直接在URL中传递产品ID参数
        
                 // 使用页面初始化时获取的产品ID
        
        $.ajax({
            url: 'http://localhost:5025/api/BOM/GetBOMOne?ProductId=' + productId,
            type: 'GET',
            success: function(response) {
                console.log('获取BOM详情成功:', response);
                if (response.code === 200 && response.data && response.data.length > 0) {
                    bomRecords = response.data; // 赋值给全局变量
                    
                    // 使用第一条记录的基本信息填充表单
                    var firstBOM = bomRecords[0];
                    
                    // 填充表单数据
                    $('input[name="boMtheme"]').val(firstBOM.bomtheme || firstBOM.boMtheme || firstBOM.BOMtheme || firstBOM.BomTheme);
                    $('input[name="bomVersion"]').val(firstBOM.bomVersion || firstBOM.BOMVersion);
                    $('select[name="productId"]').val(firstBOM.productId || firstBOM.ProductId);
                    $('input[name="dayNum"]').val(firstBOM.dayNum || firstBOM.DayNum);
                    $('textarea[name="bomDesc"]').val(firstBOM.bomDesc || firstBOM.BOMDesc);
                    $('input[name="bomState"]').prop('checked', firstBOM.bomState || firstBOM.BOMState);
                    
                    console.log('BOM数据填充完成:', firstBOM);
                    console.log('产品ID:', firstBOM.productId);
                    console.log('BOM主题:', firstBOM.bomtheme);
                    console.log('BOM版本:', firstBOM.bomVersion);
                    console.log('天数:', firstBOM.dayNum);
                    console.log('BOM描述:', firstBOM.bomDesc);
                    console.log('BOM状态:', firstBOM.bomState);
                    console.log('所有BOM记录:', bomRecords);
                    console.log('第一条BOM记录的完整数据:', JSON.stringify(firstBOM, null, 2));
                    console.log('BOM主题字段的所有可能值:');
                    console.log('  bomtheme:', firstBOM.bomtheme);
                    console.log('  boMtheme:', firstBOM.boMtheme);
                    console.log('  BOMtheme:', firstBOM.BOMtheme);
                    console.log('  BomTheme:', firstBOM.BomTheme);
                    console.log('  BOMTheme:', firstBOM.BOMTheme);
                    
                    // 重新渲染表单
                    form.render();
                    
                    // 确保下拉框正确显示
                    form.render('select');
                    
                    // 标记已选择的物料
                    setTimeout(function() {
                        console.log('开始标记已选择的物料...');
                        bomRecords.forEach(function(bomRecord) {
                            console.log('处理BOM记录:', bomRecord);
                            // 选中对应的物料行
                            var materialId = bomRecord.materialId;
                            var tableData = table.cache.materialTable;
                            console.log('查找物料ID:', materialId, '在表格数据中');
                            if (tableData) {
                                for (var i = 0; i < tableData.length; i++) {
                                    if (tableData[i].materialId === materialId) {
                                        console.log('找到匹配的物料行:', tableData[i]);
                                        // 设置选中状态
                                        tableData[i].LAY_CHECKED = true;
                                        break;
                                    }
                                }
                            }
                        });
                        // 重新渲染表格
                        console.log('重新渲染表格...');
                        table.reload('materialTable');
                        
                        // 表格重新渲染后，再次填充配件数量和损耗率
                        setTimeout(function() {
                            console.log('表格重新渲染后，开始填充配件数量和损耗率...');
                            bomRecords.forEach(function(bomRecord) {
                                var materialId = bomRecord.materialId;
                                console.log('填充物料ID:', materialId, '配件数量:', bomRecord.partNum, '损耗率:', bomRecord.lossRate);
                                $('.part-num-input[data-id="'+materialId+'"]').val(bomRecord.partNum);
                                $('.loss-rate-input[data-id="'+materialId+'"]').val(bomRecord.lossRate);
                            });
                        }, 100);
                    }, 500);
                    
                } else {
                    layer.msg(response.msg || '获取BOM详情失败', {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                console.error('获取BOM详情失败:', error);
                layer.msg('获取BOM详情失败: ' + error, {icon: 2});
            }
        });
    }
    
    // 调用初始化函数
    initMaterialTable();
    initProductSelect();
    
    // 表单提交事件
    form.on('submit(updateBOMSubmit)', function(data){
        var formData = data.field;
        
        console.log('表单原始数据:', formData);
        
        // 处理复选框值
        formData.bomState = formData.bomState === 'on' || formData.bomState === true;
        
        // 获取表格中选中的物料
        var checkStatus = table.checkStatus('materialTable');
        var selectedTableData = checkStatus.data;
        
        if(selectedTableData.length === 0){
            layer.msg('请至少选择一个物料', {icon: 2});
            return false;
        }
        
        // 获取每个选中物料的配件数量和损耗率
        var materials = [];
        for(var i = 0; i < selectedTableData.length; i++){
            var item = selectedTableData[i];
            var partNumInput = $('.part-num-input[data-id="'+item.materialId+'"]');
            var lossRateInput = $('.loss-rate-input[data-id="'+item.materialId+'"]');
            
            // 检查配件数量和损耗率是否已填写
            var partNum = partNumInput.val();
            var lossRate = lossRateInput.val();
            
            if(!partNum || partNum.trim() === ''){
                layer.msg('请填写物料 "' + item.materialName + '" 的配件数量', {icon: 2});
                return false;
            }
            
            if(!lossRate || lossRate.trim() === ''){
                layer.msg('请填写物料 "' + item.materialName + '" 的损耗率', {icon: 2});
                return false;
            }
            
            materials.push({
                materialId: item.materialId,
                partNum: parseInt(partNum),
                lossRate: lossRate.trim()
            });
        }
        
        // 构建请求数据
        var requestData = {
            productId: parseInt(formData.productId) || 0,
            boMtheme: formData.boMtheme && formData.boMtheme.trim() !== '' ? formData.boMtheme.trim() : '',
            bomVersion: formData.bomVersion && formData.bomVersion.trim() !== '' ? formData.bomVersion.trim() : '',
            materials: materials,
            dayNum: parseInt(formData.dayNum) || 0,
            bomDesc: formData.bomDesc && formData.bomDesc.trim() !== '' ? formData.bomDesc.trim() : '',
            bomState: formData.bomState || false
        };
        
        console.log('请求数据:', requestData);
        
        // 显示加载层
        var loadIndex = layer.load(1, {
            shade: [0.1,'#fff']
        });
        
        // 发送Ajax请求
        $.ajax({
            url: 'http://localhost:5025/api/BOM/UpdateBOM',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(requestData),
            success: function(response){
                layer.close(loadIndex);
                
                if(response.code === 200){
                    layer.msg('BOM修改成功！', {
                        icon: 1,
                        time: 2000
                    }, function(){
                        // 成功后跳转到列表页面
                        window.location.href = '/Home/GetBOM';
                    });
                } else {
                    layer.msg(response.msg || '修改失败：' + response.code, {
                        icon: 2,
                        time: 3000
                    });
                }
            },
            error: function(xhr, status, error){
                layer.close(loadIndex);
                
                console.error('Ajax请求失败:', xhr.responseText);
                console.error('状态码:', xhr.status);
                console.error('错误信息:', error);
                
                // 尝试解析错误响应
                try {
                    var errorResponse = JSON.parse(xhr.responseText);
                    layer.msg('修改失败：' + (errorResponse.msg || error), {
                        icon: 2,
                        time: 3000
                    });
                } catch (e) {
                    layer.msg('修改失败：' + error, {
                        icon: 2,
                        time: 3000
                    });
                }
            }
        });
        
        return false; // 阻止表单默认提交
    });
    
         // 返回列表按钮
     $('#backToList').on('click', function(){
         window.location.href = '/Home/GetBOM';
     });
     
     // 测试API按钮
     $('#testApiBtn').on('click', function(){
         console.log('测试GetBOMOne API...');
         $.ajax({
             url: 'http://localhost:5025/api/BOM/GetBOMOne?ProductId=' + productId,
             type: 'GET',
             success: function(response) {
                 console.log('API测试成功:', response);
                 console.log('第一条记录:', response.data[0]);
                 layer.msg('API连接成功', {icon: 1});
             },
             error: function(xhr, status, error) {
                 console.error('API测试失败:', xhr.responseText);
                 layer.msg('API连接失败: ' + error, {icon: 2});
             }
         });
     });
    
    // 自定义验证规则
    form.verify({
        productId: function(value, item){
            if(!value || value === ''){
                return '请选择产品';
            }
        },
        dayNum: function(value, item){
            if(value <= 0){
                return '天数必须大于0';
            }
        },
        partNum: function(value, item){
            if(value <= 0){
                return '零件数量必须大于0';
            }
        }
    });
    
         // 监听配件数量和损耗率输入框的变化
     $(document).on('input', '.part-num-input, .loss-rate-input', function(){
         var materialId = $(this).data('id');
         var value = $(this).val();
         console.log('物料ID:', materialId, '值:', value);
     });
     
     // 监听表格复选框的变化
     table.on('checkbox(materialTable)', function(obj){
         var data = obj.data;
         var materialId = data.materialId;
         
         if(obj.checked){
             // 复选框被选中时，从BOM记录中恢复配件数量和损耗率
             var bomRecord = bomRecords.find(function(record) {
                 return record.materialId === materialId;
             });
             
             if(bomRecord) {
                 console.log('复选框选中，恢复物料ID:', materialId, '的配件数量和损耗率');
                 $('.part-num-input[data-id="'+materialId+'"]').val(bomRecord.partNum);
                 $('.loss-rate-input[data-id="'+materialId+'"]').val(bomRecord.lossRate);
             }
         } else {
             // 复选框取消选中时，清空配件数量和损耗率
             console.log('复选框取消选中，清空物料ID:', materialId, '的配件数量和损耗率');
             $('.part-num-input[data-id="'+materialId+'"]').val('');
             $('.loss-rate-input[data-id="'+materialId+'"]').val('');
         }
     });
    
    
});
</script>

<style>
.layui-form {
    margin-top: 20px;
}

.layui-form-label {
    width: 100px;
}

.layui-input-block {
    margin-left: 130px;
}

.layui-textarea {
    min-height: 80px;
}

.layui-btn {
    margin-right: 10px;
}

.layui-container {
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    margin-top: 20px;
}

h2 {
    color: #333;
    border-bottom: 2px solid #5FB878;
    padding-bottom: 10px;
}

.layui-card {
    margin-top: 20px;
}

.layui-card-header {
    background-color: #f8f8f8;
    border-bottom: 1px solid #e6e6e6;
    padding: 15px 20px;
}

.layui-card-header h3 {
    margin: 0;
    color: #333;
    font-size: 16px;
    font-weight: bold;
}

 .layui-card-body {
     padding: 20px;
 }
 
 .part-num-input, .loss-rate-input {
     border: 1px solid #e6e6e6;
     border-radius: 2px;
     padding: 5px 8px;
     font-size: 12px;
 }
 
 .part-num-input:focus, .loss-rate-input:focus {
     border-color: #5FB878;
     box-shadow: 0 0 0 2px rgba(95, 184, 120, 0.2);
 }
 
 
</style>
